package org.blogwu.learn.jvmlearn.class2;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class ClassLoader2 extends ClassLoader {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ClassLoader2(String name) {
        this.name = name;
    }

    public static String path = "/Users/zsyubo/Documents/temp/jvm_learm/";

    private byte[] loadClassData(String className) {
        byte[] data = null;
        className = className.replace(".", "/");
        System.out.println("1：" + path + className + ".class");
        try (InputStream is = new FileInputStream(new File(path + className + ".class"));
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            int ch = 0;
            while (-1 != (ch = is.read())) {
                baos.write(ch);
            }
            data = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }
}
